package com.sh4.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sh4.dao.impl.UserManagerDaoImpl;
import com.sh4.dao.impl.UserRoleDaoImpl;
import com.sh4.entity.User;
import com.sh4.entity.UserRole;
import com.sh4.service.UserManagerService;
import com.sh4.util.ContextHeader;
import com.sh4.util.Sh4Utils;

import net.sf.json.JSONObject;

@Service("UserManagerServiceImpl")
@Transactional
public class UserManagerServiceImpl implements UserManagerService {
	
	@Autowired
	UserManagerDaoImpl userManagerDaoImpl;
	
	@Autowired
	UserRoleDaoImpl userRoleDaoImpl;
	
	
	

	@Override
	public int insertUser(User user) {
		// TODO Auto-generated method stub
		//获取随机数
		int random = (int)(Math.random()*10)+ 10;
		user.setPassword(Sh4Utils.getSha1(user.getPassword()+random));
		user.setSalt(""+random);
		try {
			if (user.getId() != null && user.getId().length() > 0) {
				
				user.setUpdateDate(new Date());
				user.setUpdateBy(ContextHeader.getUserCode());
				userManagerDaoImpl.saveOrUpdate(user);
				
			}else {
				user.setCreatDate(new Date());
				user.setCreatBy(ContextHeader.getUserCode());
				userManagerDaoImpl.add(user);
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			return 0;
		}
		
		return 1;
	}

	@Override
	public int deleteUserById(String userId) {
		// TODO Auto-generated method stub
		User user = new User();
		user.setId(userId);
		
		try {
			userManagerDaoImpl.delete(user);
		} catch (Exception e) {
			// TODO: handle exception
			return 0;
		}
		return 1;
	}

	@Override
	public List<User> selectedUserAll() {
		// TODO Auto-generated method stub
		List<User> users= null;
		try {
			List<User> list =  userManagerDaoImpl.selectedUserAll();
			if (list != null) {
				users = this.getUsers(list);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return users;
	}

	@Override
	public List<User> searchUsersBy(JSONObject obj) {
		// TODO Auto-generated method stub
		List<User> users= null;
		try {
			List<User> list =  userManagerDaoImpl.searchUsers(obj);
			if (list != null) {
				users = this.getUsers(list);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return users;
	}

	private List<User> getUsers(List<User> list) {
		List<User> users = new ArrayList<User>();
		for (int i = 0; i < list.size(); i++) {
			User user = new User();
			user.setId(list.get(i).getId());
			user.setCreatDate(list.get(i).getCreatDate());
			user.setCreatBy(list.get(i).getCreatBy());
			user.setEmil(list.get(i).getEmil());
			user.setUserCode(list.get(i).getUserCode());
			user.setUserName(list.get(i).getUserName());
			user.setStatus(list.get(i).getStatus());
			user.setRemark(list.get(i).getRemark());
			users.add(user);
		}
		return users;
		
	}

	@Override
	public User getUserBy(String userCode) {
		return (User) userManagerDaoImpl.getUniqueResult("from User where userCode = ?", userCode);
	}

	@Override
	public String updatePassword(JSONObject params) {
		
		String userCode = params.getString("userCode");
		String password = params.getString("password");
		String newPassword= params.getString("newPassword");
		
		User user = (User) userManagerDaoImpl.getUniqueResult("from User where userCode = ?", userCode);
		
		if(user == null) {
			return "系统不存在此用户";
		}
		
		String saltPassword = Sh4Utils.getSha1(password + user.getSalt());
		
		if(!saltPassword.equals(user.getPassword())) {
			return "密码不正确";
		}
		
		String newSaltPassword = Sh4Utils.getSha1(newPassword + user.getSalt());
		
		String hql = "update User set password = ? , updateDate = ? , updateBy = ? where userCode = ? and password = ?";
		
		userManagerDaoImpl.executeUpdate(hql, newSaltPassword, new Date( ), ContextHeader.getUserCode(),userCode,saltPassword);
		
		return "修改成功";
		
	}

	@Override
	public int addUserRole(JSONObject params) {
		// TODO Auto-generated method stub
		
		
		List<String> roleIds = (List<String>)params.getJSONArray("roleIds");
		for (int i = 0; i < roleIds.size(); i++) {
			UserRole userRole = new UserRole();
			userRole.setUserCode(params.getString("userCode"));
			userRole.setRoleId(roleIds.get(i));
			userRoleDaoImpl.saveOrUpdate(userRole);	
		}
		return 1;
	}

	@Override
	public int deleteUser(User user) {
		// TODO Auto-generated method stub
		try {
			userManagerDaoImpl.delete(user);
			userRoleDaoImpl.deleteUserRolesByUserCode(user.getUserCode());
			
		} catch (Exception e) {
			// TODO: handle exception
			return 0;
		}
		return 1;
	}
	
	@Override
	public Map<String , Object> getUserInfo(JSONObject params) {
		
		String sql = "SELECT "
				+ " u.USER_CODE_ as userCode , "
				+ " u.USER_NAME_ as userName , "
				+ " u.EMil_ as emil , "
				+ " u.CREATE_DATE_ as createDate , "
				+ " u.REMARK_ as remark ,"
				+ " f.HTTP_URL_ as imageUrl "
				+ " FROM user u "
				+ " LEFT JOIN ifiles f ON(F.LINK_ID_ = u.USER_CODE_ AND f.DELETE_FLAG_ = '0')"
				+ " where u.USER_CODE_ = ?";
		
		
		return userManagerDaoImpl.getUniqueResultBySql(sql,params.getString("userCode"));
	}
	
	@Override
	public void updateUserInfo(JSONObject params) {
		
		String hql = "update User u set u.userName = ? , u.emil = ? where u.userCode = ?";
		 userManagerDaoImpl.executeUpdate(hql, params.getString("userName"),params.getString("emil"),params.getString("userCode"));
		 
		 if(params.containsKey("imageUrl") && StringUtils.isNotEmpty(params.getString("imageUrl"))) {
			 
			 //更新这个用户曾经使用过的额头像为删除状态
			 userManagerDaoImpl.executeUpdate("update Ifiles set deleteFlag = ? where linkId = ?", "1",params.getString("userCode"));
			 
			 String fileHql = "update Ifiles f set f.linkId = ? , f.deleteFlag = ? , f.updateDate = ? ,f.updateBy = ? where f.id = ?";
			 userManagerDaoImpl.executeUpdate(fileHql, params.getString("userCode"),"0",new Date(),
					 ContextHeader.getUserCode(),params.getString("fileId"));
		 }
		 
	}
}
